<script lang="ts" setup>
import {
  closeToast,
  showConfirmDialog,
  showLoadingToast,
  showToast,
  type ActionSheetAction,
} from 'vant'
import { onMounted, ref } from 'vue'
import b64toBlob from 'b64-to-blob'
import { request } from '@/apis'

//用户资料
const userInfo = ref<UserInfoData>({} as UserInfoData)
const birthdayArray = ref(['2000', '05', '05'])

const minDate = new Date(1970, 1, 1)
const maxDate = new Date(2026, 1, 1)
onMounted(() => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  //获取用户信息
  const res = jky.getUser()
  console.log(res)
  userInfo.value = res
  birthdayArray.value = res.birthday.split('-')
  console.log(birthdayArray)
  closeToast()
})

const isShowAvatarPopup = ref(false)
const onConfirm = async (action: ActionSheetAction, index: number) => {
  // console.log(action, index)
  if (index === 0) {
    //拍照
    const res = await jky.takePhoto()
    // console.log(res)
    if (!res) {
      isShowAvatarPopup.value = false
      return
    }
    onUpdateAvatar(res)
  }
  if (index === 1) {
    //本地选择
    const res = await jky.pickerPhoto()
    // console.log(res)
    if (!res) {
      isShowAvatarPopup.value = false
      return
    }
    onUpdateAvatar(res)
  }
}

// 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    // 关闭头像选择面板
    isShowAvatarPopup.value = false
    // showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    // 将Base64编码的头像数据转换为二进制Blob对象
    const image = b64toBlob(data, 'image/jpeg')
    // 创建FormData对象用于构造multipart/form-data请求体
    const fd = new FormData()
    // 'file'是接口约定的参数名，将Blob对象添加到FormData中
    fd.append('photo', image, Date.now() + '.jpeg')

    showLoadingToast({
      message: '加载中',
      forbidClick: true,
    })

    // 发起POST请求上传头像
    const res = await request.patch<AvatarRes>('/v1_0/user/photo', fd)
    console.log(res, 'base')

    // 更新本地用户信息的头像URL
    userInfo.value.photo = URL.createObjectURL(image)

    // 获取当前用户信息,用来跟新鸿蒙端
    const user = jky.getUser()

    // // 更新用户头像URL为服务器返回的URL
    // .avatar = res.data.result.avatar
    userInfo.value.photo = res.data.data.photo

    // // 更新用户信息到鸿蒙端
    jky.updateUserInfo(user)

    // 显示上传成功提示
    showToast({ message: '上传成功' })
    closeToast()
  } catch (err) {
    // 显示上传失败提示
    console.log(err)
    closeToast()
  }
}

//退出登录
const logout = () => {
  showConfirmDialog({
    title: '温馨提示',
    message: '亲，您确定要退出吗？',
  })
    .then(() => {
      jky.logout()
      jky.goLogin()
      jky.getUser()
    })
    .catch(() => {})
}

//昵称编辑
const showOverlayNikeName = ref(false)
const submitUserInfoName = async () => {
  // if (!userInfo.value.name) {
  //   showToast({ message: '请输入昵称' })
  //   return
  // }
  showOverlayNikeName.value = false
  showOverlayintro.value = false
  showLoadingToast({
    message: '加载中',
    forbidClick: true,
  })
  await request.request<UserInfoData>({
    url: '/v1_0/user/profile',
    method: 'PATCH',
    data: userInfo.value,
  })
  showToast({ message: '修改成功' })
  closeToast()
}
const openNicknameEdit = () => {
  showOverlayNikeName.value = true
  document.title = '修改昵称'
}
//简介编辑
const showOverlayintro = ref(false)
const openIntroEdit = () => {
  showOverlayintro.value = true
  document.title = '修改简介'
}

//生日编辑
const isShowSexPopup = ref(false)
const selectSex = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    userInfo.value.gender = 0
  }
  if (index === 1) {
    userInfo.value.gender = 1
  }
  showLoadingToast({
    message: '加载中',
    forbidClick: true,
  })
  await request.request<UserInfoData>({
    url: '/v1_0/user/profile',
    method: 'PATCH',
    data: userInfo.value,
  })
  showToast({ message: '修改成功' })
  jky.getUser()
  isShowSexPopup.value = false
  closeToast()
}

//生日编辑
const isShowBirthdayPopup = ref(false)
const confirmBirthday = async (data: { selectedValues: number[] }) => {
  console.log(data.selectedValues)
  userInfo.value.birthday = data.selectedValues.join('-')
  showLoadingToast({
    message: '加载中',
    forbidClick: true,
  })
  await request.request<UserInfoData>({
    url: '/v1_0/user/profile',
    method: 'PATCH',
    data: userInfo.value,
  })
  showToast({ message: '修改成功' })
  jky.getUser()
  isShowBirthdayPopup.value = false
  closeToast()
}
</script>

<template>
  <div style="background-color: '#f0f0f0'">
    <!-- //头像编辑 -->
    <van-action-sheet
      v-model:show="isShowAvatarPopup"
      :actions="[{ name: '拍照' }, { name: '本地选择' }]"
      @select="onConfirm"
      cancel-text="取消"
    ></van-action-sheet>

    <!-- 昵称编辑 -->
    <van-overlay :show="showOverlayNikeName">
      <div class="wrapper">
        <div class="block" @click.stop>
          <div style="padding: 16px">
            <van-field v-model="userInfo.name" label="您的昵称" placeholder="请输入昵称" />
            <button @click="submitUserInfoName" class="submitUserInfoNameStyles">提交</button>
            <button @click="showOverlayNikeName = false" class="submitUserInfoNameStyles">
              取消
            </button>
          </div>
        </div>
      </div>
    </van-overlay>

    <!-- 简介编辑 -->
    <van-overlay :show="showOverlayintro">
      <div class="wrapper">
        <div class="block" @click.stop>
          <div style="padding: 16px">
            <van-field
              v-model="userInfo.intro"
              rows="4"
              autosize
              label="个人简介"
              type="textarea"
              placeholder="请输入简介"
            />
            <button @click="submitUserInfoName" class="submitUserInfoNameStyles">提交</button>
            <button @click="showOverlayintro = false" class="submitUserInfoNameStyles">取消</button>
          </div>
        </div>
      </div>
    </van-overlay>

    <!--性别编辑  -->
    <van-action-sheet
      v-model:show="isShowSexPopup"
      :actions="[{ name: '男' }, { name: '女' }]"
      @select="selectSex"
      cancel-text="取消"
    ></van-action-sheet>

    <!-- 生日编辑 -->
    <van-popup v-model:show="isShowBirthdayPopup" position="bottom">
      <van-date-picker
        v-model="birthdayArray"
        title="选择生日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="isShowBirthdayPopup = false"
        @confirm="confirmBirthday"
      />
    </van-popup>

    <!-- ================================ -->
    <van-cell title="头像" is-link @click="isShowAvatarPopup = true">
      <template #value>
        <van-image :src="userInfo.photo" round width="30" height="30"></van-image>
      </template>
    </van-cell>

    <van-cell title="昵称" is-link :value="userInfo.name" @click="openNicknameEdit" />

    <van-cell
      title="简介"
      is-link
      :value="userInfo?.intro?.trim() ? userInfo.intro : '暂无简介'"
      @click="openIntroEdit"
    />

    <van-cell
      title="性别"
      @click="isShowSexPopup = true"
      is-link
      :value="userInfo.gender === 0 ? '男' : '女'"
    />
    <van-cell title="生日" is-link :value="userInfo.birthday" @click="isShowBirthdayPopup = true" />

    <!-- 退出登录按钮 -->
    <div class="logout-button">
      <button @click="logout">退出登录</button>
    </div>
  </div>
</template>

<style scoped>
/* 可以添加一些自定义样式 */
#app {
  position: relative; /* 使 .logout-button 相对于 #app 定位 */
  min-height: 100vh; /* 确保 #app 至少占满整个视口高度 */
  box-sizing: border-box; /* 包含 padding 和 border 在内 */
  padding-bottom: 60px; /* 为底部按钮预留空间 */
}

.logout-button {
  position: absolute;
  bottom: 50px; /* 距离底部 20px */
  left: 50%; /* 水平居中 */
  transform: translateX(-50%); /* 水平居中 */
}

.logout-button button {
  padding: 10px 20px;
  font-size: 16px;
  color: #ff6c6c; /* 文字颜色 */
  background-color: transparent; /* 透明背景 */
  border: none;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
.submitUserInfoNameStyles {
  width: 100%;
  height: 40px;
  color: #ff6c6c;
  border: none;
  background-color: transparent; /* 透明背景 */
}
</style>
